<template>
    <div class="form-page">
      
       
      <div class="form-group">
  
  
  
        <!-- 添加其他 pin 数据字段 -->
  
  
        <form @submit="handleSubmit">
  
  
         
          <div class="form-group">
          <label>name:</label>
          <input type="text" v-model="Name">
        </div>
  
                <!-- 合约符号 -->
        <div class="form-group">
          <label>symbol:</label>
          <input type="text" v-model="Symbol">
        </div>

        <div class="form-group">
          <label>decimals:</label>
          <input type="text" v-model="Decimals">
        </div>
          
        <div class="form-group">
          <label>address:</label>
          <input type="text" v-model="Management">
        </div>

        <div class="form-group">
          <label>uri:</label>
          <input type="text" v-model="Uri">
        </div>
  
    
      
        <button type="submit">提交</button>
        
        </form>
     
     
    </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import {
          notify
      } from "@kyvg/vue3-notification";
   //交互
   import * as anchor from "@coral-xyz/anchor";
  
  //import { Nftmint } from "../types/nftmint";
  import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram ,LAMPORTS_PER_SOL} from "@solana/web3.js";
  import { AnchorError } from '@coral-xyz/anchor';
  import { ASSOCIATED_PROGRAM_ID, TOKEN_PROGRAM_ID, associatedAddress } from "@coral-xyz/anchor/dist/cjs/utils/token";
  import { BN } from "bn.js";
  
  import { useWallet } from 'solana-wallets-vue'
  const METADATA_PROGRAM = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
  
  import store from './../vuex';
  
  
  
   const Name = ref('cc');
   const Symbol = ref('cc');
   const Decimals = ref('9');
   const Management = ref('CA8dyZ1cBsUH98BSy8FraXSRNKb72tkUsSaPL6zdY57Y');
   const Uri = ref('https://ipfs.io/ipfs/QmXRBh1hEBZvUUG49DmsvtWqg6zqYrREKkXNWG3VnDciZz');
  
  async function create() {
    const workspaceValue = store.state.workspace.value;
  if (!workspaceValue) {
    console.error('Workspace is not initialized.');
    return;
  }
  
  //组装数据
  

  const name = Name.value;
  const symbol = Symbol.value;
  const decimals =  Number(Decimals.value);
  const recipient = new PublicKey(Management.value);//购买预售时的ticket
  const uri = Uri.value;
  
  let timestamp = Math.floor(new Date().getTime() / 1000);
  
  
  const { wallet, connection, provider, program } = workspaceValue;
  console.log("program.programId:",program.programId);
  const mint = anchor.web3.Keypair.generate();//初始化一个token mint
    console.log("mint", mint.publicKey.toBase58());
    const recipient_token =  associatedAddress({
      mint: mint.publicKey,//代币地址
      owner: recipient//运营
    });//运营关联的token地址
    const fund_pool = PublicKey.findProgramAddressSync([Buffer.from("fund_pool"), mint.publicKey.toBuffer()], program.programId)[0];//资金池 存1000w token
    const lp_pool = PublicKey.findProgramAddressSync([Buffer.from("lp_pool"), mint.publicKey.toBuffer()], program.programId)[0];//用户质押池 token
    const blind_box = PublicKey.findProgramAddressSync([Buffer.from("blind_box"), mint.publicKey.toBuffer()], program.programId)[0];//token 盲盒
    let metadata = anchor.web3.PublicKey.findProgramAddressSync(
      [Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), mint.publicKey.toBytes()],
      METADATA_PROGRAM
    )[0];//代币的metadata地址
    const modifyComputeUnits = anchor.web3.ComputeBudgetProgram.setComputeUnitLimit({
      units: 500_000,
    });//设置计算单位
  
  
    try {
  
        const tx = await program.methods
      .initializeMint(
        {
          name: name,//token名称
          symbol: symbol,//token简称
          uri: uri,//token元数据地址
          decimals: decimals,//token精度
        }
      )
      .accounts({
        mintAuthority: provider.wallet.publicKey,//一般运营来初始化
        mint: mint.publicKey,//token mint
        recipient: recipient,//运营 或指定一个钱包地址来收1100w token
        recipientToken: recipient_token,//运营 或指定一个钱包地址 的代币关联地址
        fundPool: fund_pool,//资金池
        lpPool: lp_pool,//用户质押池
        metadata: metadata,//代币的metadata地址
        blindBox: blind_box,//token 盲盒
        tokenProgram: TOKEN_PROGRAM_ID,
        tokenMetadataProgram: METADATA_PROGRAM,
        associatedTokenProgram: ASSOCIATED_PROGRAM_ID,
        systemProgram: SystemProgram.programId,
        rent: SYSVAR_RENT_PUBKEY,
      })
      .signers([mint])
      .preInstructions([modifyComputeUnits])
      .rpc();
  
    console.log("Your transaction signature", tx);
  
  
   } catch (error) {
      
     if (error instanceof AnchorError) {
       
       
       const code = error.error.errorCode.code ;
       const number = error.error.errorCode.number ;
        const  message = error.error.errorMessage;
       
       console.error('捕获到的错误: ', code,number,message);
       // 在这里处理错误，例如显示错误消息给用户
     } else {
       // 处理其他类型的错误
       console.error('未知错误: ', error);
     }
   }
  
  }
  
  
  // ...您可能需要添加一些方法来处理表单提交...
  // 添加一个方法来处理表单提交
  const handleSubmit = async (event) => {
  // 阻止表单的默认提交行为
    event.preventDefault();
 
  
    store.commit('initWorkspace', {
        callback: () => {
          create();
        }
      });
  
  
  
  };
  </script>
  
  <style scoped>
  .form-page {
  color: #ffffff; /* 文字颜色为白色，以提高对比度 */
  background-color: #333333; /* 表单页面背景颜色 */
  padding: 20px; /* 添加内边距 */
  border-radius: 8px; /* 添加圆角 */
  width: 80%; /* 调整宽度为屏幕的80% */
  max-width: 700px; /* 最大宽度限制 */
  margin: 20px auto; /* 增加上下边距并水平居中 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  }
  
  .form-group {
  margin-bottom: 15px; /* 减少底部边距 */
  }
  
  label {
  display: block;
  margin-bottom: 5px; /* 减少标签下边距 */
  color: #bbbbbb; /* 标签文字颜色稍微淡一些，以区分输入框 */
  font-size: 0.9em; /* 减小字体大小 */
  }
  
  .data-display {
  padding: 10px;
  background-color: #444444; /* 数据显示背景颜色 */
  color: #dddddd; /* 数据显示文字颜色 */
  border-radius: 4px; /* 数据显示圆角 */
  margin-bottom: 10px; /* 数据显示下边距 */
  word-wrap: break-word; /* 防止内容溢出 */
  }
  
  input[type="number"],
  input[type="text"],
  input[type="datetime-local"] {
  width: 100%; /* 调整宽度为100% */
  padding: 10px;
  background-color: #444444; /* 输入框背景颜色 */
  color: #dddddd; /* 输入框文字颜色 */
  border: 1px solid #555555; /* 输入框边框颜色 */
  border-radius: 4px; /* 输入框圆角 */
  box-sizing: border-box; /* 确保宽度包括内边距和边框 */
  }
  
  button {
  padding: 10px 20px;
  background-color: #0056b3; /* 按钮背景颜色 */
  color: white;
  border: none;
  border-radius: 4px; /* 按钮圆角 */
  cursor: pointer;
  transition: background-color 0.3s; /* 添加过渡效果 */
  font-size: 0.9em; /* 减小字体大小 */
  margin-top: 15px; /* 减少按钮上边距 */
  }
  
  button:hover {
  background-color: #004080; /* 鼠标悬停时的按钮背景颜色 */
  }
  
  .pin-image {
  display: block;
  max-width: 100%; /* 确保图片不会超出容器宽度 */
  height: auto; /* 高度自动调整 */
  margin-top: 15px; /* 在图片上方添加间距 */
  border-radius: 4px; /* 图片圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 为图片添加阴影 */
  }
  </style>
  
  